package action;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import model.Department;
import model.Message;
import model.User;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.github.miemiedev.mybatis.paginator.domain.PageList;

import service.DeptService;
import service.MessageService;
import util.SaveFile;
import action.base.BaseAction;

@Controller
@Scope("prototype")
public class MessageAction extends BaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Autowired
	private MessageService messageService;
	@Autowired
	private DeptService deptService;
	private Message message;
	private boolean success;
	private int total;
	private PageList<HashMap<String, Object>> pageList;
	private List<HashMap<String, Object>> receivers;
	private File file;
	// 获取上传文件的名称
	private String fileFileName;
	private InputStream stream;
	private Integer msgId;
	private Integer msgCount;

	public String saveOrUpdate() {
		String receids = super.getParameterStr("receiverId");
		String operation = super.getParameterStr("operation");
		String deleteids = super.getParameterStr("deleteids");
		HashMap<String, Object> map = new HashMap<String, Object>();
		User user = super.getUser();
		message.setSenderid(user.getId());
		message.setSendername(user.getName());
		messageService
				.saveOrUpdate(message, receids, operation, deleteids, map);
		String filePath = saveFile();
		message.setAttach(filePath);
		message.setAttachname(fileFileName);
		map.put("filePath", filePath);
		map.put("fileFileName", fileFileName);
		messageService
				.saveOrUpdate(message, receids, operation, deleteids, map);
		setSuccess(true);
		return "save";
	}

	public String saveFile() {
		Integer _fname;
		if (msgId == null) {
			_fname = message.getId();
		} else {
			_fname = msgId;
		}

		SaveFile sf = new SaveFile();
		String path = super.getContext().getRealPath(
				"\\uploadFiles\\messageFiles\\f_");

		String filePath = null;
		String fname = _fname.toString();
		if (file != null && file.exists() && file.length() > 0) {
			filePath = sf.save2Server(fname, file, path);
		}
		return filePath;
	}

	public String down() throws Exception {
		Integer id = super.getParameterInt("msgid");
		String fname = super.getParameterStr("fileName");
		message = messageService.getById(id);
		if (StringUtils.isNotEmpty(message.getAttach())) {
			String attach = message.getAttach();
			File f = new File(attach);
			if (f.exists()) {
				setStream(new FileInputStream(f));

			} else
				return "noFile";
		} else
			return "noFile";
		success = true;
		fileFileName = fname;
		return "down";

	}

	/**
	 * 删除个人草稿或已发送信息，改变状态为3
	 * 
	 * @return
	 */
	public String delete() {
		String ids = super.getParameterStr("ids");
		messageService.delete(ids);
		setSuccess(true);
		return "success";
	}

	public String queryPage() {
		User user = super.getUser();
		Integer status = super.getParameterInt("status");
		int page = super.getParameterInt("page");
		int limit = super.getParameterInt("limit");
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("userid", user.getId());
		if (status != null && status.equals(0)) {
			status = null;
		}
		map.put("status", status);
		pageList = messageService.queryPage(page, limit, map);
		setTotal(pageList.getPaginator().getTotalCount());
		return "queryPage";
	}

	public String queryMyPage() {
		User user = super.getUser();
		Integer status = super.getParameterInt("status");
		int page = super.getParameterInt("page");
		int limit = super.getParameterInt("limit");
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("userid", user.getId());
		if (status != null && status.equals(0)) {
			status = null;
		}
		map.put("status", status);
		pageList = messageService.queryMyPage(page, limit, map);
		setTotal(pageList.getPaginator().getTotalCount());
		return "queryPage";
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public String queryReceiver() {
		int page = super.getParameterInt("page");
		int limit = super.getParameterInt("limit");
		String deptId = super.getParameterStr("deptId");
		String recids = super.getParameterStr("recids");
		HashMap<String, Object> map = new HashMap<String, Object>();
		ArrayList deptIds = new ArrayList();
		ArrayList ids = new ArrayList();
		if (StringUtils.isNotBlank(deptId)) {
			deptIds.add(Integer.parseInt(deptId));
			List<Department> getByPid = deptService.getTreeBypid(Integer
					.parseInt(deptId));
			if (getByPid.size() != 0) {
				for (int i = 0; i < getByPid.size(); i++) {
					// deptIds[i] = getByPid.get(i).getId();
					deptIds.add(getByPid.get(i).getId());
				}
			}
		}
		if (deptIds.size() == 0 || deptId.equals("1")) {
			deptIds = null;
		}
		map.put("deptIds", deptIds);
		if (StringUtils.isNotBlank(recids)) {
			String[] _ids = recids.split(",");
			for (String item : _ids) {
				ids.add(item);
			}
		}
		User user = super.getUser();
		ids.add(user.getId());
		map.put("ids", ids);
		pageList = messageService.queryReceiver(page, limit, map);
		setTotal(pageList.getPaginator().getTotalCount());
		return "queryReceiver";
	}

	/**
	 * 读取个人已收信息，改变状态为2
	 * 
	 * @return
	 */
	public String read() {
		Integer messid = super.getParameterInt("messid");
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("id", messid);
		map.put("status", 2);
		map.put("readtime", new Date());
		messageService.read(map);
		setSuccess(true);
		return "success";
	}

	/**
	 * 删除个人已收信息，改变状态为3
	 * 
	 * @return
	 */
	public String deleteMy() {
		String myids = super.getParameterStr("myids");
		messageService.deleteMy(myids);
		setSuccess(true);
		return "success";
	}

	public String getById() {
		Integer messageId = super.getParameterInt("messageId");
		message = messageService.getById(messageId);
		setSuccess(true);
		return "message";
	}

	public String queryReceivers() {
		Integer messageId = super.getParameterInt("messageId");
		receivers = messageService.queryReceivers(messageId);
		setSuccess(true);
		return "receivers";
	}

	public String msgCount() {
		User user = super.getUser();
		msgCount = messageService.msgCount(user.getId());
		setSuccess(true);
		return "msgCount";
	}

	public Message getMessage() {
		return message;
	}

	public void setMessage(Message message) {
		this.message = message;
	}

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public PageList<HashMap<String, Object>> getPageList() {
		return pageList;
	}

	public List<HashMap<String, Object>> getReceivers() {
		return receivers;
	}

	public void setReceivers(List<HashMap<String, Object>> receivers) {
		this.receivers = receivers;
	}

	public void setPageList(PageList<HashMap<String, Object>> pageList) {
		this.pageList = pageList;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public InputStream getStream() {
		return stream;
	}

	public void setStream(InputStream stream) {
		this.stream = stream;
	}

	public Integer getMsgId() {
		return msgId;
	}

	public void setMsgId(Integer msgId) {
		this.msgId = msgId;
	}

	public Integer getMsgCount() {
		return msgCount;
	}

	public void setMsgCount(Integer msgCount) {
		this.msgCount = msgCount;
	}

}
